package com.example.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Looper;
import android.widget.Toast;

public class AudioMediaPlayer {

    private android.media.MediaPlayer mp;
    private Context context;
    private String word0;
    private int type0;
    private int last_type=-1;//记录上一次的播放类型
    private String last_word="";//记录上一次的单词

    public AudioMediaPlayer(Context context){
        this.context=context;
        System.out.println("音频初始化");
        }

        //更新音频和播放
    public void updateMP(String word, int type){
        this.word0=word;
        this.type0=type;
        //Log.i("hahaha","调用该UpdateMP方法");
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (type0 != last_type || word0 != last_word) {
                    if(isNetworkAvailable(context)) {//判断是否联网,如果联网
                        Uri location = Uri.parse("http://dict.youdao.com/dictvoice?type=0&audio=" + word0);
                        mp = android.media.MediaPlayer.create(context, location);
                        mp.start();
                    }
                }else {//不更换音频
                     if(isNetworkAvailable(context)) {//判断是否联网,如果联网
                         if (!mp.isPlaying()) {//判断是否在播放
                             mp.start();
                         }
                     }else {
                         Looper.prepare();
                         Toast.makeText(context,"没有联网,不可播放音频！",Toast.LENGTH_SHORT).show();
                         Looper.loop();
                     }
            }
                last_type=type0;
                last_word=word0;
        }}).start();

    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                //这里可以得到网络状态网络类型等网络相关信息
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }
}

